#!/usr/bin/python3

# coding=utf-8

# Created: 2022-10-29
# Updated: 2022-10-29
# Author : comet
# Description: get temperature and humidity by dht sensor, and publish to MQTT
# pin 3.3v(1) GPIO4(7) GND(9)

import logging
import json
import adafruit_dht
import paho.mqtt.client as mqtt

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(name)s] %(levelname)8s %(message)s')

with open("dht.conf", 'r') as load_file:
    load_dict = json.load(load_file)

MQTT_SERVICE_HOST = load_dict['mqtt']['hostname']
MQTT_SERVICE_PORT = load_dict['mqtt']['port']
MQTT_SERVICE_CLIENT_ID = load_dict['mqtt']['clientid']
MQTT_SERVICE_USER = load_dict['mqtt']['username']
MQTT_SERVICE_PASSWORD = load_dict['mqtt']['password']
MQTT_SERVICE_TOPIC = load_dict['mqtt']['topic']
SENSOR_TYPE = load_dict['sensor']['type'].lower()
SENSOR_PIN = load_dict['sensor']['pin']
SENSOR_INTERVAL = load_dict['sensor']['interval']

if SENSOR_TYPE == 'dht22':
    sensor = adafruit_dht.DHT22
elif SENSOR_TYPE == 'dht11':
    sensor = adafruit_dht.DHT11
else:
    raise Exception('Supported sensor types: DHT22, DHT11')

logger = logging.getLogger(MQTT_SERVICE_CLIENT_ID)

if __name__ == "__main__":

    # Display config on startup
    logger.debug("#" * 80)
    logger.debug(f"# {SENSOR_PIN=}")
    logger.debug(f"# {SENSOR_INTERVAL=}")
    logger.debug(f"# {MQTT_SERVICE_HOST=}")
    logger.debug(f"# {MQTT_SERVICE_PORT=}")
    logger.debug(f"# {MQTT_SERVICE_USER=}")
    logger.debug(f"# {MQTT_SERVICE_PASSWORD=}")
    logger.debug(f"# {MQTT_SERVICE_TOPIC=}")
    logger.debug(f"# {MQTT_SERVICE_CLIENT_ID=}")
    logger.debug("#" * 80)

    # Initializes DHT on given GPIO pin
    dht_sensor = sensor(SENSOR_PIN)
    client = mqtt.Client()
    client.username_pw_set(username=MQTT_SERVICE_USER, password=MQTT_SERVICE_PASSWORD)
    client.connect(host=MQTT_SERVICE_HOST, port=MQTT_SERVICE_PORT)
    try:
        # Read from sensor
        temperature = dht_sensor.temperature
        humidity = dht_sensor.humidity
    except RuntimeError as e:
        logger.error(str(e))

    logger.info(f"[{MQTT_SERVICE_TOPIC}] -- {temperature}°C,{humidity}% --> [{MQTT_SERVICE_HOST}:{MQTT_SERVICE_PORT}]")
    try:
        # Prepare messages to be published on MQTT
        data = {'temperature': str(temperature), 'humidity': str(humidity)}
        # Publish messages on given MQTT broker
        client.publish(MQTT_SERVICE_TOPIC, json.dumps(data))
    except Exception:
        logger.error("An error occured publishing values to MQTT", exc_info=True)

